package com.thinkgem.jeesite.common.frame.rpc.factory;

import com.thinkgem.jeesite.common.frame.rpc.annotation.RPCWebService;
import com.thinkgem.jeesite.common.frame.rpc.annotation.RPCBeanDefinition;
import com.thinkgem.jeesite.common.utils.ClassPathScanUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;

/**
 * Created by liufeng on 2016/6/6.
 */
public class RPCWebServiceFactory {

    private static transient Log logger = LogFactory.getLog(RPCWebServiceFactory.class);

    private static Map<String,RPCBeanDefinition> beanDefinitionMap = new HashMap<String, RPCBeanDefinition>();

    public static void scanWebService() {

        logger.debug("------------开始扫描WebService--------------");
        String webServicePath = ResourceBundle.getBundle("rpc").getString("rpcWebService");
        ClassPathScanUtil util = new ClassPathScanUtil();
        Set<Class<?>> classList = util.getPackageAllClasses(webServicePath, true);
        for (Class<?> aClass : classList) {

            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                if (method.isAnnotationPresent(RPCWebService.class)) {
                    RPCWebService annotation = method.getAnnotation(RPCWebService.class);
                    String webServiceName = annotation.value();
                    double webServiceVersion = annotation.version();
                    if (StringUtils.isBlank(webServiceName)) {
                        continue;
                    }
                    RPCBeanDefinition rpcBeanDefinition = new RPCBeanDefinition.Builder().addName(webServiceName).addClassRef(aClass).addMethodRef(method).addVersion(webServiceVersion).builder();
                    beanDefinitionMap.put(webServiceName,rpcBeanDefinition);

                }
            }


        }


    }


    public static RPCBeanDefinition getRPCWebService(String path) {
        if(!beanDefinitionMap.containsKey(path)){
            return null;
        }else {
            return beanDefinitionMap.get(path);
        }

    }
}
